<template>
  <div class="table-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery.supplier"
        placeholder="搜索供应商"
        class="search-input"
        @input="handleSearch"
      />
      <el-input
        v-model="searchQuery.productName"
        placeholder="搜索商品名称"
        class="search-input"
        @input="handleSearch"
      />
      <el-input
        v-model="searchQuery.productLink"
        placeholder="搜索商品链接"
        class="search-input"
        @input="handleSearch"
      />
      <el-input
        v-model="searchQuery.localId"
        placeholder="搜索商品本地编号"
        class="search-input"
        @input="handleSearch"
      />
    </div>

    <!-- 商品列表 -->
    <div class="table-wrapper">
      <el-table
        v-if="totalProducts > 0"
        :data="paginatedProducts"
        style="width: 100%"
        border
        stripe
      >
        <!-- 图片列 -->
        <el-table-column label="图片" width="120" class-name="no-truncate">
          <template slot-scope="scope">
            <div class="image-preview">
              <img
                v-for="(image, i) in scope.row.productImage"
                :key="i"
                :src="image"
                alt="商品图片"
                class="preview-image"
                @click="openModal(image)"
              />
            </div>
          </template>
        </el-table-column>

        <!-- 供应商列 -->
        <el-table-column
          prop="supplier"
          label="供应商"
          class-name="no-truncate"
        />

        <!-- 商品名称列 -->
        <el-table-column
          prop="productName"
          label="商品名称"
          class-name="no-truncate"
        >
          <template slot-scope="scope">
            <a :href="scope.row.link" target="_blank">{{
              scope.row.productName
            }}</a>
          </template>
        </el-table-column>

        <!-- 颜色列 -->
        <el-table-column prop="color" label="颜色" width="100" />

        <!-- 尺码列 -->
        <el-table-column prop="size" label="尺码" width="100" />

        <!-- 价格列 -->
        <el-table-column label="价格" width="300">
          <template slot-scope="scope">
            <table class="transparent-table">
              <tr>
                <td>代发：</td>
                <td>{{ formatNumber(scope.row.price1) }}</td>
                <td>{{ formatNumber(scope.row.price2) }}</td>
                <td>{{ formatNumber(scope.row.price3) }}</td>
                <td>{{ formatNumber(scope.row.price4) }}</td>
                <td>{{ formatNumber(scope.row.price5) }}</td>
              </tr>
              <tr>
                <td>邮费：</td>
                <td>{{ formatNumber(scope.row.shipping1) }}</td>
                <td>{{ formatNumber(scope.row.shipping2) }}</td>
                <td>{{ formatNumber(scope.row.shipping3) }}</td>
                <td>{{ formatNumber(scope.row.shipping4) }}</td>
                <td>{{ formatNumber(scope.row.shipping5) }}</td>
              </tr>
              <tr>
                <td><span class="expense">成本：</span></td>
                <td>
                  <span class="expense">{{
                    calculateCost(scope.row.price1, scope.row.shipping1)
                  }}</span>
                </td>
                <td>
                  <span class="expense">{{
                    calculateCost(scope.row.price2, scope.row.shipping2)
                  }}</span>
                </td>
                <td>
                  <span class="expense">{{
                    calculateCost(scope.row.price3, scope.row.shipping3)
                  }}</span>
                </td>
                <td>
                  <span class="expense">{{
                    calculateCost(scope.row.price4, scope.row.shipping4)
                  }}</span>
                </td>
                <td>
                  <span class="expense">{{
                    calculateCost(scope.row.price5, scope.row.shipping5)
                  }}</span>
                </td>
              </tr>
              <tr>
                <td><span class="earnings">售价：</span></td>
                <td>
                  <span class="earnings">{{
                    calculateSellingPrice(scope.row.price1, scope.row.shipping1)
                  }}</span>
                </td>
                <td>
                  <span class="earnings">{{
                    calculateSellingPrice(scope.row.price2, scope.row.shipping2)
                  }}</span>
                </td>
                <td>
                  <span class="earnings">{{
                    calculateSellingPrice(scope.row.price3, scope.row.shipping3)
                  }}</span>
                </td>
                <td>
                  <span class="earnings">{{
                    calculateSellingPrice(scope.row.price4, scope.row.shipping4)
                  }}</span>
                </td>
                <td>
                  <span class="earnings">{{
                    calculateSellingPrice(scope.row.price5, scope.row.shipping5)
                  }}</span>
                </td>
              </tr>
            </table>
          </template>
        </el-table-column>

        <!-- 评分列 -->
        <el-table-column prop="recommendStar" label="评分" width="100" />

        <!-- 本地编号列 -->
        <el-table-column prop="localId" label="本地编号" width="100" />

        <!-- 评论列 -->
        <el-table-column
          prop="productOpinion"
          label="评论"
          class-name="no-truncate"
        />

        <!-- 抖店商品ID列 -->
        <el-table-column label="抖店商品ID" class-name="no-truncate">
          <template slot-scope="scope">
            <div
              v-for="(item, index) in scope.row.relatedDYProductIds.split(',')"
              :key="index"
            >
              {{ item }},
            </div>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <router-link
              :to="`/form?productId=${scope.row.id}`"
              class="el-button el-button--text"
              >编辑</router-link
            >
            <el-button type="text" @click="confirmDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <el-pagination
      v-if="totalProducts > 0"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalProducts"
      class="pagination"
    />

    <!-- 图片放大预览模态框 -->
    <div v-if="isModalOpen" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <img :src="selectedImage" alt="放大预览" class="modal-image" />
        <button class="close-button" @click="closeModal">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
import { add, multiply, round } from "mathjs"; // 引入 math.js 的 add 和 multiply 方法

export default {
  data() {
    return {
      products: [], // 存储商品列表数据
      isModalOpen: false, // 控制模态框的显示与隐藏
      selectedImage: "", // 当前选中的图片
      searchQuery: {
        supplier: "",
        productName: "",
      },
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的数量
      totalProducts: 0, // 总条数
    };
  },
  async created() {
    // 组件创建时加载商品列表
    await this.fetchProducts();
  },
  methods: {
    // 打开模态框
    openModal(image) {
      this.selectedImage = image;
      this.isModalOpen = true;
    },
    // 关闭模态框
    closeModal() {
      this.isModalOpen = false;
      this.selectedImage = "";
    },
    async fetchProducts() {
      try {
        const es_index = "swin_storage";
        const param = {
          from: (this.currentPage - 1) * this.pageSize, // 分页起始位置
          size: this.pageSize, // 每页大小
          query: {
            bool: {
              must: [
                {
                  match_all: {}, // 默认查询所有数据
                },
              ],
            },
          },
          sort: [
            {
              _id: {
                order: "desc", // 按 _id 降序排序
              },
            },
          ],
        };

        // 如果有搜索条件，添加到查询中
        if (
          this.searchQuery.supplier ||
          this.searchQuery.productName ||
          this.searchQuery.productLink ||
          this.searchQuery.localId
        ) {
          param.query.bool.must = [];
          if (this.searchQuery.supplier) {
            param.query.bool.must.push({
              wildcard: {
                "supplier.keyword": `*${this.searchQuery.supplier.toLowerCase()}*`, // 模糊查询供应商
              },
            });
          }
          if (this.searchQuery.productName) {
            param.query.bool.must.push({
              wildcard: {
                "productName.keyword": `*${this.searchQuery.productName.toLowerCase()}*`, // 模糊查询商品名称
              },
            });
          }
          if (this.searchQuery.productLink) {
            param.query.bool.must.push({
              wildcard: {
                link: `*${this.searchQuery.productLink}*`, // 模糊查询链接名称
              },
            });
          }
          if (this.searchQuery.localId) {
            param.query.bool.must.push({
              wildcard: {
                localId: `*${this.searchQuery.localId}*`, // 模糊查询链接名称
              },
            });
          }
        }

        const response = await fetch(`/api/${es_index}/_search`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(param),
        });

        const data = await response.json();
        this.products = data.hits.hits.map((hit) => ({
          ...hit._source,
          id: hit._id,
        }));
        this.totalProducts = data.hits.total; // 获取总条数
        console.log("商品列表更新完成：", this.products);
      } catch (error) {
        console.error("加载商品列表失败：", error);
        alert("加载商品列表失败，请检查网络或后端服务。");
      }
    },
    async deleteProduct(id) {
      const es_index = "swin_storage";
      const param = {
        query: {
          term: {
            _id: `${id}`,
          },
        },
      };
      await fetch(
        `/api/${es_index}/_delete_by_query?refresh=true&conflicts=proceed`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(param),
        }
      )
        .then((response) => {
          // 处理响应
          if (!response.ok) {
            throw new Error("网络请求失败");
          }
          return response.json(); // 解析 JSON 数据
        })
        .then((data) => {
          if (data.deleted === 1) {
            console.log("删除成功");
          }
          this.fetchProducts();
          // 处理解析后的数据
          console.log("请求成功，数据为：", data);
        })
        .catch((error) => {
          // 处理错误
          console.error("请求失败：", error);
        });
    },
    confirmDelete(id) {
      if (confirm("确定要删除该商品吗？")) {
        this.deleteProduct(id);
      }
    },
    // 格式化数字，保留两位小数
    formatNumber(value) {
      return round(Number(value), 2);
    },
    // 计算成本
    calculateCost(price, shipping) {
      return round(add(Number(price), Number(shipping)), 2);
    },
    // 计算售价
    calculateSellingPrice(price, shipping) {
      const cost = add(Number(price), Number(shipping));
      const sellingPrice = add(multiply(cost, 2), 8);
      return round(sellingPrice, 2);
    },
    // 处理搜索
    handleSearch() {
      this.currentPage = 1; // 重置到第一页
      this.fetchProducts(); // 重新获取数据
    },
    // 处理每页显示数量变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1; // 重置到第一页
      this.fetchProducts(); // 重新获取数据
    },
    // 处理页码变化
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchProducts(); // 重新获取数据
    },
  },
  computed: {
    // 计算当前页显示的商品列表
    paginatedProducts() {
      return this.products; // 直接返回过滤后的商品列表
    },
  },
};
</script>

<style scoped>
/* 表格容器样式 */
.table-container {
  width: 100%;
  padding: 20px;
}

/* 搜索栏样式 */
.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  width: 200px;
}

/* 表格包裹容器 */
.table-wrapper {
  width: 100%;
  overflow-x: auto; /* 横向滚动 */
}

/* 图片预览样式 */
.image-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.preview-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border: 1px solid #ccc;
  border-radius: 4px;
  cursor: pointer;
}

/* 自适应宽度列 */
.no-truncate .cell {
  white-space: nowrap; /* 不换行 */
  overflow: visible; /* 不截断 */
  text-overflow: clip; /* 不显示省略号 */
}

/* 响应式设计 */
@media (max-width: 600px) {
  .search-bar {
    flex-direction: column;
  }

  .search-input {
    width: 100%;
  }

  .preview-image {
    width: 30px;
    height: 30px;
  }
}

.expense {
  color: green;
}

.earnings {
  color: #ff0000;
}

.clickable {
  cursor: pointer;
  color: red;
  text-decoration: underline;
}

/* 设置内层透明表格样式 */
.transparent-table {
  border-collapse: collapse;
  width: 100%;
  background: transparent; /* 使表格背景透明 */
}

.transparent-table td {
  border: 0px solid #ddd; /* 设置表格边框为淡灰色 */
  padding: 5px; /* 设置单元格内边距 */
  text-align: left; /* 文字居左显示 */
  background: transparent; /* 单元格背景透明 */
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  position: relative;
  max-width: 90%;
  max-height: 90%;
  overflow: auto;
}

.modal-image {
  max-width: 100%;
  max-height: 80vh;
  display: block;
  margin: 0 auto;
}

.close-button {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #ff0000;
  color: #fff;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
}

.close-button:hover {
  background-color: #cc0000;
}

/* 分页样式 */
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>